package com.luoying.itew.activity;

import android.app.IntentService;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.UserHandle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;

import com.luoying.itew.R;
import com.luoying.itew.common.Constant;
import com.luoying.itew.databinding.ActivityMainChangeBinding;
import com.luoying.itew.event.JPushEvent;
import com.luoying.itew.event.LoginEvent;
import com.luoying.itew.fragment.BaseFragment;
import com.luoying.itew.fragment.ListDataFragment;
import com.luoying.itew.fragment.MapFragment;
import com.luoying.itew.fragment.MineFragment;
import com.luoying.itew.util.DialogUtils;
import com.luoying.itew.util.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lufan on 2019-05-23
 * Class describe
 */
public class MainActivity extends BaseActivity<ActivityMainChangeBinding> implements View.OnClickListener {
    /**
     * Tag
     */
    private static final String TAG = "MainActivity";
    /**
     * 退出类型
     */
    final String EXIT_TYPE = "exit_type";
    /**
     * 退出标记
     */
    final int EXIT_TYPE_INDEX = 1001;
    /**
     * 极光绑定标示
     */
    public static final int BINDING_SEQUENCE = 1002;
    /**
     * 极光解除绑定标示
     */
    public static final int UMBINDING_SEQUENCE = 1003;
    /**
     * 地图类型
     */
    public static final int TYPE_MAP = 0;
    /**
     * 列表类型
     */
    public static final int TYPE_LIST = 1;
    /**
     * 我的
     */
    public static final int TYPE_MINE = 2;

    private final Class[] frgs = new Class[]{MapFragment.class, ListDataFragment.class,MineFragment.class};

    /**
     * 当前的fragment
     */
    private Fragment currentFragment;

    /**
     * 当前选择的类型
     */
    private int currentIndex = -1;

    /**
     * model
     */
    private MainActivityViewModel model;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_main_change;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void init() {
        super.init();
        //注册EventBus事件
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        model = ViewModelProviders.of(this).get(MainActivityViewModel.class);

        switcTab(TYPE_MAP);
        model.getWeather().observe(this, this::setWeatherInfo);
        model.getUserInfo().observe(this, userInfo -> {
//            if(JPushInterface.isPushStopped(getApplicationContext())){
//               JPushInterface.resumePush(getApplicationContext());
//            }
            //获取用户信息成功开始绑定极光推送
            JPushInterface.setAlias(getApplicationContext(),BINDING_SEQUENCE,userInfo.getUserId() + "");
        });
        model.getUpdateBean().observe(this, updateRBean -> {
            if(updateRBean==null||!updateRBean.isIsUpgrade()){
                if(currentFragment instanceof MineFragment){
                    Toast.makeText(this,"当前是最新版本",Toast.LENGTH_SHORT).show();
                }
            } else {
                DialogUtils.showUpdateDialog(this,updateRBean.getAppVersionDownload(),updateRBean.isIsImposedUpgrade());
            }
        });
        model.getWeatherInfo();
        startActivity(null);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("")
                .build();
        try {
            Response response = client.newCall(request).execute();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {


                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 改变底部菜单栏
     * @param index
     */
    public void switcTab(int index){
        if(index==currentIndex){
            return;
        }
        viewBinding.mainCbMap.setChecked(false);
        viewBinding.mainCbMine.setChecked(false);
        viewBinding.mainCbList.setChecked(false);
        if(index==TYPE_MAP){
            viewBinding.mainCbMap.setChecked(true);
            viewBinding.titleTv.setText(R.string.title_map);
        }
        if(index==TYPE_LIST){
            viewBinding.mainCbList.setChecked(true);
            viewBinding.titleTv.setText(R.string.title_list_data);
        }
        if(index==TYPE_MINE){
            viewBinding.mainCbMine.setChecked(true);
            viewBinding.titleTv.setText(R.string.title_mine);
        }
        switchFragment(index);
    }

    /**
     * 切换Fragment
     * @param index 下标
     */
    public void switchFragment (int index){
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        BaseFragment target = (BaseFragment) getSupportFragmentManager().findFragmentByTag(frgs[index].toString());
        if(target==null){
            try {
                target = (BaseFragment)frgs[index].newInstance();
                if (currentFragment == null) {
                    transaction.add(R.id.root_view,target, target.getClass().toString());
                } else {
                    transaction.hide(currentFragment).add(R.id.root_view,target,target.getClass().toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else{
            if (currentFragment == null) {
                transaction.add(R.id.root_view,target, target.getClass().toString());
            } else if (target.isAdded()) {//如果已经被加载 隐藏当前的 显示现在的
                transaction.hide(currentFragment).show(target);
            } else {
                transaction.hide(currentFragment).add(R.id.root_view, target, target.getClass().toString());
            }
        }
        transaction.commitAllowingStateLoss();
        currentFragment = target;
    }

    /**
     * 获取天气
     */
    private void setWeatherInfo(String s){
        viewBinding.titleWeather.setText(s);
        if(TextUtils.isEmpty(s)){
            return;
        }
        if (s.contains("雨")){
            //雨天
            Drawable drawable = getResources().getDrawable(R.drawable.rain);
            viewBinding.titleWeather.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
        } else if (s.equals("多云")){
            //多云
            Drawable drawable = getResources().getDrawable(R.drawable.cloud);
            viewBinding.titleWeather.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
        }else {
            //晴天
            Drawable drawable = getResources().getDrawable(R.drawable.lightrain);
            viewBinding.titleWeather.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
        }
    }

    /**
     * 账号token失效主动退出登录
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void singleLoginOut(LoginEvent event){
        if(event.getLoginType()==LoginEvent.LOGIN_STATE_SINGLE){
            EventBus.getDefault().unregister(this);
            //使用singleTask启动模式当前activity，清除其他所有activity
            Intent intent = new Intent(this, this.getClass());
            intent.putExtra(EXIT_TYPE, EXIT_TYPE_INDEX);
            startActivity(intent);
        }
    }

    /**
     * 极光绑定结果事件
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void jPushResult(JPushEvent event){
        if (event.getErrorCode() == 0){
            LogUtils.d(TAG,"别名设置成功");
            //提交绑定
            model.jigrangBind();
        }else {
            LogUtils.d(TAG,"别名设置失败，ErrorCode == " +event.getErrorCode());
        }
    }

     /**
     * 这里用singleTask启动模式清除所有Activity后退出当前主界面
     * @param intent
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if(intent!=null&&intent.getIntExtra(EXIT_TYPE,0)==EXIT_TYPE_INDEX){
            //token失效退出登录
            loginOut(Constant.LOGOUT_TYPE_OFFLINE);
        }
    }

    /**
     * 退出登录
     * @param flag
     */
    public void loginOut(int flag){
        Intent intent = new Intent(this,LoginActivity.class);
        intent.putExtra("from", 1);
        startActivity(intent);
        this.finish();
        model.logout(flag);
        JPushInterface.deleteAlias(getApplicationContext(),UMBINDING_SEQUENCE);
//        //停止极光服务
//        JPushInterface.stopPush(getApplicationContext());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.main_fl_map:
            case R.id.main_cb_map:
                switcTab(TYPE_MAP);
                break;
            case R.id.main_fl_list:
            case R.id.main_cb_list:
                switcTab(TYPE_LIST);
                break;
            case R.id.main_fl_mine:
            case R.id.main_cb_mine:
                switcTab(TYPE_MINE);
                break;
        }

    }

    @Override
    public synchronized ComponentName startForegroundServiceAsUser(Intent service, UserHandle user) {
        return null;
    }
}
